package org.lojzes.lojzesframework.factory;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Set;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;
/**
 * 通过注解定义bean
 * @author Administrator
 *
 */
public class PreDaoClassPathBeanScanner extends ClassPathBeanDefinitionScanner{

	public PreDaoClassPathBeanScanner(BeanDefinitionRegistry registry,Class<? extends Annotation> annotation) {
		super(registry);
		addIncludeFilter(new AnnotationTypeFilter(annotation));
	}

	@Override
	protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	  Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
      if (beanDefinitions.isEmpty()) {
           System.err.println("没有找到此"+Arrays.toString(basePackages)+" 下的dao接口！");
      }
      GenericBeanDefinition definition = null;
      for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitions) {
    	  definition = (GenericBeanDefinition)beanDefinitionHolder.getBeanDefinition();
    	  definition.getPropertyValues().add("classInterface", definition.getBeanClassName());
    	  definition.getPropertyValues().add("handler", getRegistry().getBeanDefinition("preDaoHandler"));
    	  definition.setBeanClass(PreDaoBeanFactory.class);
	  }
		return beanDefinitions;
	}

	protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
		return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent();
	}
}
